package webServlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.user.domain.User;
import cn.user.domain.dao.UserDao;

/**
 * Servlet implementation class loginServlet
 */
@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {


	private static final long serialVersionUID = 1L;

	public loginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8"); // �����������ݱ���
		String check = request.getParameter("checkCode"); // ��ȡ������֤����Ϣ
		String username = request.getParameter("username");
		//System.out.println(request.getSession().getAttribute("checkCode"));
		if (check.equalsIgnoreCase((String) request.getSession().getAttribute("checkCode"))) {
			request.getSession().removeAttribute("checkCode");
			try {
				// �ж��û���������
				int passint = Integer.parseInt(request.getParameter("password"));
				User user0 = new User();
				user0.setUsername(username);
				user0.setPass(passint);
				UserDao tset = new UserDao();
				User user_information = tset.login(user0);
				if (user_information == null) {
					// ��¼ʧ�ܣ��洢��¼��Ϣ������ת������¼ҳ��
					request.setAttribute("user_error", "true");
					request.getRequestDispatcher("/Login.jsp").forward(request, response);
				} else {
					// ��¼�ɹ�,�洢user��Ϣ���ض�������¼�ɹ�ҳ��
					request.getSession().setAttribute("user_inf", user_information);
					// response.setStatus(302);
					response.sendRedirect(request.getContextPath() + "/first.html");

				}
			} catch (NumberFormatException e) {
				request.setAttribute("user_error", "true");
				request.getRequestDispatcher("/Login.jsp").forward(request, response);
			}
		}

		else {
			// ��֤�벻��ȷ���洢��ʾ��Ϣ����������ת������¼ҳ��
			
			request.setAttribute("check_error", "true");
			//System.out.println(request.getAttribute("check_error"));
			request.getRequestDispatcher("/Login.jsp").forward(request, response);

		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
